import { Component, OnInit, Output, EventEmitter } from '@angular/core';
import { Router, NavigationEnd, ActivatedRoute } from '@angular/router';
import { LoginService } from '../shared/services/login.service';

@Component({
  selector: 'app-dashboard',
  templateUrl: './dashboard.component.html',
  styleUrls: ['./dashboard.component.scss']
})
export class DashboardComponent implements OnInit {
  formartMenu = new EventEmitter();

  breadcrumb: Array<object>;

  user: any;

  constructor(
    private router: Router,
    private loginService: LoginService,
    private route: ActivatedRoute,
  ) {
    this.breadcrumb = [
      { name: '菜谱', lv: 0, url: '' },
    ];

    router.events.subscribe(event => {
      if (event instanceof NavigationEnd) {
        // console.log('url', event);
        // console.log('param', route.snapshot);
        // 筛选出router
        let pageComponent = route.snapshot;
        let index = 0;
        while (pageComponent.children.length > 0) {
          pageComponent = pageComponent.children[0];
          index++;
        }
        // console.log('index', index);
        // console.log('component', pageComponent);
        if (pageComponent.data && pageComponent.data.name !== 'eyoule' && this.formartData(pageComponent.data)) {
          if (pageComponent.data.lv === 1) {
            this.breadcrumb = [];
            this.breadcrumb.push({ name: '菜谱', lv: 0, url: '' });
            this.breadcrumb.push(pageComponent.data);
          } else {
            this.breadcrumb.push(pageComponent.data);
          }
        }
        if (pageComponent.data.name === 'eyoule') {
          this.breadcrumb = [];
          this.breadcrumb.push({ name: '菜谱', lv: 0, url: '' });
        }
      }
    });
  }

  ngOnInit() {
    // 获取当前登录用户
    this.user = this.loginService.getUser();
    if (!this.user) {
      this.router.navigate(['login']);
    }
  }

  breadcrumbHref(a) {
    if (a.lv === 0) {
      this.formartMenu.emit('clear');
    }
    if (this.breadcrumb.findIndex(i => i['name'] === a.name) === (this.breadcrumb.length - 1)) {
      return false;
    }
    this.breadcrumb = this.breadcrumb.slice(0, this.breadcrumb.findIndex(i => i['name'] === a.name));
    this.router.navigate(['dashboard/' + a.url]);
  }

  formartData(data) {
    let bool = true;
    this.breadcrumb.forEach(i => {
      if (i['name'] === data['name']) {
        bool = false;
      }
    });
    return bool;
  }

  signOut() {
    this.loginService.signOut();
    this.router.navigate(['login']);
  }

}
